package com.huilink.webmail.util.client.widgets;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DelegatingClickListenerCollection;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.MouseListenerAdapter;
import com.google.gwt.user.client.ui.Widget;
import com.huilink.webmail.util.client.WidgetEnabled;

public class ImageButton extends FocusPanel implements WidgetEnabled{
	private Image imgOff;

    private String off;
    private String on;
    private String disabled;
    
    private String text;
    private String name;
    
    private boolean isEnabled = true;
    
    private DelegatingClickListenerCollection clickListeners;
    

    public ImageButton(String off, String on, int width , int height) 
    {
        this(off, on, null, width, height);
    }
    
    public ImageButton(String off, String on, String disabled, int width , int height) 
    {
        super();
        initImages(on , off, width, height);
        initListeners();
        setWidget(imgOff);
        setSize(width+"px", height+"px");
        this.on = on;
        this.off = off;
        this.disabled = disabled;
        imgOff.addStyleName("default-image-button");
    }
    
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
    private void initImages(String on, String off, int width , int height) {
        imgOff = buildImage(off, width, height);
    }

    private Image buildImage(String img, int width, int height) {
        Image res = new Image(img);
        res.setSize(width+"px", height+"px");
        return res;
    }

    private void initListeners() {
        imgOff.addMouseListener(new MouseListenerAdapter() {

            public void onMouseEnter(Widget sender) {
                imgOff.setUrl(on);
            }
            public void onMouseLeave(Widget sender) {
                imgOff.setUrl(off);
            }

        });

    }

    public void setText(String text){
    	this.text = text;
    	imgOff.setTitle(text);
    }
    
    public String getText(){
    	return text;
    }
    
    public void setEnabled(boolean isEnabled)
    {
    	this.isEnabled  = isEnabled;
    	
    	if (isEnabled)
    	{
    		imgOff.setUrl(off);
    		imgOff.sinkEvents(WidgetEnabled.EVENT);
    		sinkEvents(WidgetEnabled.EVENT);
    	}
    	else
    	{
    		imgOff.setUrl(disabled);
    		imgOff.unsinkEvents(WidgetEnabled.EVENT);
    		unsinkEvents(WidgetEnabled.EVENT);
    	}
    }
    
    public boolean isEnabled()
    {
    	return isEnabled;
    }

	public void addClickListener(ClickListener listener) {
		if (clickListeners == null) {
			clickListeners = new DelegatingClickListenerCollection(this, imgOff);
		}
		clickListeners.add(listener);
	}
}
